﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace IP20.Procdure
{
    /// <summary>
    /// 测试数量统计类
    /// </summary>
    [XmlRoot("测试数量统计")]
    [Serializable]
    public class Counter
    {
        private static readonly object locker = new object();
        private static readonly string file = "counter.xml";

        static Counter()
        {
#if JQ8931314
            file = "counter2.xml";
#endif
        }

        [XmlElement("NG数量")]
        public int NgCount { get; set; }

        [XmlElement("OK数量")]
        public int OkCount { get; set; }

        public static Counter Load()
        {
            try
            {
                if (!File.Exists(file))
                {
                    Counter c = new Counter { OkCount = 1, NgCount = 1 };
                    Save(c);
                    return c;
                }

                using (TextReader reader = new StreamReader(file))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(Counter));
                    return serializer.Deserialize(reader) as Counter;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载计数器失败: {ex.Message}");
                return new Counter(); // 返回空实例
            }
        }

        public static void Save(Counter counter)
        {
            lock (locker)
            {
                if (counter is null)
                    throw new ArgumentNullException(nameof(counter));

                //string tempFile = Path.GetTempFileName();
                try
                {
                    using (TextWriter writer = new StreamWriter(file))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(Counter));
                        serializer.Serialize(writer, counter);
                    }
                    //File.Replace(file, tempFile, null);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"保存计数器失败: {ex.Message}");
                    throw;
                }
                finally
                {
                    //if (File.Exists(tempFile))
                    //    File.Delete(tempFile);
                }
            }
        }
    }
}